<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代号" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入代号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>      
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.asset_stock_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['asset:stock:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="代号" align="center" prop="name">
          <template slot-scope="scope">
          <router-link :to="'/asset/stock/do/' + scope.row.id" class="link-type" v-if="scope.row.status != '4'">
            <span>{{ scope.row.name }}</span>
          </router-link>
          <router-link :to="'/asset/stock/detail/' + scope.row.id" class="link-type" v-if="scope.row.status == '4'">
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="资产数" align="center" prop="asset_count" />
      <el-table-column label="资产总值" align="center" prop="asset_worth" />
      <el-table-column label="报废数" align="center" prop="scrap_count" />
      <el-table-column label="报废总值" align="center" prop="scrap_worth" />
      <el-table-column label="出售数" align="center" prop="sale_count" />
      <el-table-column label="出售总值" align="center" prop="sale_worth" />
      <el-table-column label="开始时间" align="center" prop="start_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.start_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="end_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.end_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="进度状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.asset_stock_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status != '4' && scope.row.status != '3'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['asset:stock:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.status == '3'"
            size="mini"
            type="danger"
            icon="el-icon-check"
            @click="handleCheck(scope.row)"
            v-hasPermi="['asset:stock:edit']"
          >确认</el-button>
          <el-button v-if="scope.row.status == '1'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['asset:stock:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />
    <!-- 添加或修改资产盘点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-tabs v-model="tab">
        <el-tab-pane label="任务信息" name="base">
        <el-form-item label="代号" prop="name">
          <el-input v-model="form.name" placeholder="请输入代号" readonly/>
        </el-form-item>
         <el-form-item label="开始时间" prop="start_time">
          <el-date-picker clearable readonly
            v-model="form.start_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker clearable readonly
            v-model="form.end_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <template v-for="dict in dict.type.asset_stock_status">
            <el-radio v-if="dict.value != '4'"              
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
            </template>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="盘点说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="盘点结果" name="result" v-if="form.id">
            <el-form-item label="资产总数" prop="asset_count">
          <el-input v-model="form.asset_count" placeholder="请输入资产总数" />
        </el-form-item>
        <el-form-item label="资产总值" prop="asset_worth">
          <el-input v-model="form.asset_worth" placeholder="请输入资产总值" />
        </el-form-item>
        <el-form-item label="报废总数" prop="scrap_count">
          <el-input v-model="form.scrap_count" placeholder="请输入报废总数" />
        </el-form-item>
        <el-form-item label="报废总值" prop="scrap_worth">
          <el-input v-model="form.scrap_worth" placeholder="请输入报废总值" />
        </el-form-item>
        <el-form-item label="出售数量" prop="sale_count">
          <el-input v-model="form.sale_count" placeholder="请输入出售数量" />
        </el-form-item>
        <el-form-item label="出售总值" prop="sale_worth">
          <el-input v-model="form.sale_worth" placeholder="请输入出售总值" />
        </el-form-item>
        </el-tab-pane>
        </el-tabs>                
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <import-dialog :open="upload" model="asset_stock" @cancel="importCancel" @success="importSuccess" />
  </div>
</template>

<script>
import { apiGet, apiPost, apiPut, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";
import ImportDialog from "@/components/ImportDialog";

export default {
  name: "Stock",
  components: {
    ImportDialog
  },
  dicts: ['asset_stock_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产盘点表格数据
      stockList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        name: null,
        start_time: null,
        end_time: null,
        user_id: null,
        "@alias": "t",
        "@exp": {
            // 代号搜索
            name: 'lk'
        }
      },
      pager: {
        page: 1,
        limit: 10,
        order: "id desc",
      },
      // 导入参数
      upload: false,
      // 表单参数
      form: {},
      tab: 'base',
      // 表单校验
      rules: {
        name: [
          { required: true, message: "代号不能为空", trigger: "blur" }
        ],
        start_time: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        end_time: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询资产盘点列表 */
    getList() {
      this.loading = true;
      let params = {};
      params['asset_stock'] = {... this.queryParams};
      params['@pager'] = this.pager;
      apiGet(params).then(response => {
        this.stockList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: this.parseTime(new Date(), '{y}-{m}-{d}'),
        asset_count: null,
        asset_worth: null,
        scrap_count: null,
        scrap_worth: null,
        sale_worth: null,
        sale_count: null,
        remark: null,
        start_time: null,
        end_time: null,
        user_id: null,
        status:"1"
      };
      this.resetForm("form");
      this.tab = 'base';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资产盘点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        let data = {};
        data['asset_stock'] = { id:id};
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资产盘点";
      });      
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data = {};
          data['asset_stock'] = this.form;
          data['@tags'] = ['asset_stock'];
          if (this.form.id != null) {
            apiPut(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            apiPost(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },    
    /** 确认按钮操作 */
    handleCheck(row) {        
        let that = this;
        apiDs('asset_stock_undone', {stockId: row.id}).then(response=>{
            if(response.data == null || parseInt(response.data) == 0){
                that.$modal.confirm('确认盘点任务后，将同步更新资产信息为盘点后的状态，您确认是否继续操作？').then(function() {
                    let data = {
                        'asset_stock': {
                        id: row.id,
                        status: "4"
                        },
                        "@tags": ['asset_stock']
                    };
                    apiPut(data).then(response => {
                        that.$modal.msgSuccess("确认成功");
                        that.getList();
                    });
                });
            }else{
                this.$modal.msgError("当前任务还有 " + response.data +" 个资产需要盘点");
                return;
            }
        });
        
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的资产盘点数据？').then(function() {
        let data = {};
        data['asset_stock'] = { id:ids, "@exp":{id:"in"}};
        data['@tags'] = ['asset_stock','asset_stock_detail'];
        data['asset_stock_detail'] = { stock_id:ids, "@exp":{stock_id:"in"}};
        return apiDelete(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload = true;
    },
    importSuccess(msg) {
        this.upload = false;
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
    },
    importCancel() {
        this.upload = false;
    },
    /** 导出按钮操作 */
    handleExport() {
        let params = {};
      params['asset_stock'] = {... this.queryParams};
      params['@pager'] = {page:1, limit:10000};
      apiExport(params).then(response => {
        apiDownload(response.msg);
      });
    }
  }
};
</script>
